package com.wu.ssm.spring.utils;

import com.wu.ssm.spring.mvc.bean.Multipart;
import com.wu.ssm.spring.mvc.bean.Multiparts;
import com.wu.ssm.spring.mvc.bean.Params;
import com.wu.ssm.spring.mvc.fault.UploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

/**
 * Created by wzf on 2018/12/20/020.
 */
public class UploadHelper {
    private static final Logger logger = LoggerFactory.getLogger(UploadHelper.class);
    private static ServletFileUpload fileUpload;

    public UploadHelper() {
    }

    public static void init(ServletContext servletContext) {
        File repository = (File)servletContext.getAttribute("javax.servlet.context.tempdir");
        logger.debug("[Smart] temp dir of uploading: {}", repository);
        fileUpload = new ServletFileUpload(new DiskFileItemFactory(10240, repository));
        int uploadLimit = 5000;
        if (uploadLimit != 0) {
            fileUpload.setFileSizeMax((long)(uploadLimit * 1024 * 1024));
            logger.debug("[Smart] limit of uploading: {}M", uploadLimit);
        }

    }

    public static boolean isMultipart(HttpServletRequest request) {
        return ServletFileUpload.isMultipartContent(request);
    }

    public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception {
        List<Object> paramList = new ArrayList();
        Map<String, Object> fieldMap = new HashMap();
        ArrayList multipartList = new ArrayList();

        List fileItemList;
        try {
            fileItemList = fileUpload.parseRequest(request);
        } catch (FileUploadBase.FileSizeLimitExceededException var14) {
            throw new UploadException(var14);
        }

        Iterator i$ = fileItemList.iterator();

        while(i$.hasNext()) {
            FileItem fileItem = (FileItem)i$.next();
            String fieldName = fileItem.getFieldName();
            String fileName;
            if (fileItem.isFormField()) {
                fileName = fileItem.getString("UTF-8");
                fieldMap.put(fieldName, fileName);
            } else {
                fileName = FileUtil.getRealFileName(fileItem.getName());
                if (StringUtil.isNotEmpty(fileName)) {
                    long fileSize = fileItem.getSize();
                    String contentType = fileItem.getContentType();
                    InputStream inputSteam = fileItem.getInputStream();
                    Multipart multipart = new Multipart(fieldName, fileName, fileSize, contentType, inputSteam);
                    multipartList.add(multipart);
                }
            }
        }

        paramList.add(new Params(fieldMap));
        paramList.add(new Multiparts(multipartList));
        return paramList;
    }

    public static void uploadFile(String basePath, Multipart multipart) {
        try {
            if (multipart != null) {
                String filePath = basePath + multipart.getFileName();
                System.out.println(filePath);
                FileUtil.createFile(filePath);
                String suffix = multipart.getFileName().substring(multipart.getFileName().lastIndexOf(".") + 1);
                System.out.println(suffix);
                InputStream inputStream = new BufferedInputStream(multipart.getInputStream());
                OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
                StreamUtil.copyStream(inputStream, outputStream);
            }

        } catch (Exception var5) {
            logger.error("上传文件出错！", var5);
            throw new RuntimeException(var5);
        }
    }

    public static void uploadFiles(String basePath, Multiparts multiparts) {
        Iterator i$ = multiparts.getAll().iterator();

        while(i$.hasNext()) {
            Multipart multipart = (Multipart)i$.next();
            uploadFile(basePath, multipart);
        }

    }
}
